package com.cictec.middleware.tde.rm.disp.receiver.handler;

import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.cictec.middleware.commons.utils.BinaryUtils;
import com.cictec.middleware.feign.distribute.MiddlewarePassengerFlowService;
import com.cictec.middleware.tde.rm.disp.annotation.HandleMessages;
import com.cictec.middleware.tde.rm.disp.receiver.AbstractReceiverHandler;
import com.cictec.middleware.tde.rm.protocol.TerminalMessage;
import com.cictec.middleware.tde.rm.protocol.rm.message.Rm0x41TerminalMessage;

/**
 * 上传透明通通道数据（接收指令应答确认）【已在AutoResponseFilter中配置回复应答】
 * 
 * @author Administrator
 *
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Component
@HandleMessages(0x41)
public class TerminalPassThroughHandler extends AbstractReceiverHandler {

	public static Logger logger = LoggerFactory.getLogger(TerminalPassThroughHandler.class);

	@Autowired
	private MiddlewarePassengerFlowService middlewarePassengerFlowService;

	@Override
	public void handleMessage(TerminalMessage message, IoSession session) {

		Rm0x41TerminalMessage msg = (Rm0x41TerminalMessage) message;

		// 0x80 指令应答 收到需要应答的数据包
		sendMessageToTerminal(createResponse(message), session);

		logger.debug("【0x41 上传透明通通道数据】终端 {}  Session {} ", message.getTerminalId(), message.getSessionId());
		logger.debug("【0x41 上传透明通通道数据】设备类型:{}", msg.getDeviceType());
		if (msg.getDeviceType() == 0xe0) {
			// 处理客流统计的透传数据。
			logger.debug("【0x41 上传透明通通道数据】收到设备{} 客流数据:{}", msg.getTerminalId(), BinaryUtils.byte2HexStr(msg.getData()));

			try {
				// 解析客流数据
				Map data = getPassengerFlowResult(msg);
				logger.debug("【0x41 上传透明通通道数据】收到设备{} 解析后数据:{}", msg.getTerminalId(), JSON.toJSONString(data));

//				middlewarePassengerFlowService.rmPassengerFlowUpload(msg.getTerminalId(), JSON.toJSONString(data));

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				logger.error("客流数据处理报错: {}", e);
			}
		}
	}

	/**
	 * 解析客流数据，并组装称数据存储对象
	 * 
	 * @param msg
	 * @return
	 */

	public Map getPassengerFlowResult(Rm0x41TerminalMessage msg) {

		Map data = new HashMap();
		data.put("pfrUploadTime", msg.getCreateTime());

		// 定义空byte[]
		byte[] noMes = null;

		ByteBuffer buffer = ByteBuffer.wrap(msg.getData());
		// 设备编号
		byte[] devIdByte = new byte[3];
		buffer.get(devIdByte);
		data.put("prfDevUuid", String.valueOf(BinaryUtils.threeBytesToInt(devIdByte)));
		byte[] lineTypebyte = new byte[1];
		buffer.get(lineTypebyte);
		// passengerFlowResult.setPfrLineType(String.valueOf(BinaryUtils.unsignedByteToInt(lineTypebyte[0]))); // 接受的原始上下行信息 0:上行,1:下行
		String lineType = String.valueOf(BinaryUtils.unsignedByteToInt(lineTypebyte[0]));
		data.put("prfLineType", lineType.equals("0") ? "1" : "2");

		byte[] stationSqn = new byte[2];
		buffer.get(stationSqn);
		data.put("prfStationSeq", String.valueOf(BinaryUtils.wordToInt(stationSqn)));
		int endFlagInt = 0;
		byte[] pfrData = new byte[1];
		buffer.get(pfrData);
		int packHead = BinaryUtils.unsignedByteToInt(pfrData[0]);
		if (packHead == 126) {
			do {
				noMes = new byte[1];
				buffer.get(noMes);
				byte[] fdoorByte = new byte[1];
				buffer.get(fdoorByte);
				int fdoorInt = BinaryUtils.unsignedByteToInt(fdoorByte[0]);
				// 前门
				if (fdoorInt == 160) {
					noMes = new byte[7];
					buffer.get(noMes);
					byte[] fdoorInByte = new byte[1];
					buffer.get(fdoorInByte);
					int fOn = BinaryUtils.unsignedByteToInt(fdoorInByte[0]);
					logger.debug("前门上车：{}", fOn);
					data.put("prfGetFOnNumber", fOn);
					byte[] fdoorOffByte = new byte[1];
					buffer.get(fdoorOffByte);
					int fOFF = BinaryUtils.unsignedByteToInt(fdoorOffByte[0]);
					logger.debug("前门下车：{}", fOFF);
					data.put("prfGetFOffNumber", fOFF);
				} else if (fdoorInt == 161) {// 中门
					noMes = new byte[7];
					buffer.get(noMes);
					byte[] fdoorInByte = new byte[1];
					buffer.get(fdoorInByte);
					int fon = BinaryUtils.unsignedByteToInt(fdoorInByte[0]);
					logger.debug("中门上车：{}", fon);
					data.put("prfGetCOnNumber", fon);
					byte[] fdoorOffByte = new byte[1];
					buffer.get(fdoorOffByte);

					int foff = BinaryUtils.unsignedByteToInt(fdoorOffByte[0]);
					logger.debug("中门下车：{}", foff);
					data.put("prfGetCOffNumber", foff);
				} else if (fdoorInt == 162) {// 后门
					noMes = new byte[7];
					buffer.get(noMes);
					byte[] fdoorInByte = new byte[1];
					buffer.get(fdoorInByte);
					int eOn = BinaryUtils.unsignedByteToInt(fdoorInByte[0]);
					data.put("prfGetEOnNumber", eOn);
					logger.debug("后门上车：{}", eOn);
					byte[] fdoorOffByte = new byte[1];
					buffer.get(fdoorOffByte);
					int eOff = BinaryUtils.unsignedByteToInt(fdoorOffByte[0]);
					logger.debug("后门下车：{}", eOff);
					data.put("prfGetEOffNumber", eOff);
				}
				noMes = new byte[3];
				buffer.get(noMes);
				byte[] endFlag = new byte[1];
				buffer.get(endFlag);
				endFlagInt = BinaryUtils.unsignedByteToInt(endFlag[0]);
			} while (endFlagInt != 33);
		}

		String devDataString = BinaryUtils.byte2HexStr(msg.getData());
		data.put("prfDevDatastring", devDataString);
		logger.debug("客流原始数据{}", devDataString);
		return data;
	}

}
